package main

import (
	"ImageServer/config"
	"ImageServer/utils"
	"encoding/json"
	"github.com/google/uuid"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"
	"time"
)

// 82fcd88c4e720412
// 5934d5e4-9cae-40f3-9a21-3d4ceb8399c2
func main() {
	err := config.InitConfig()
	if err != nil {
		log.Panic("read config file error :", err.Error())
	}
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
	http.Handle("/image/", http.StripPrefix("/image/", http.FileServer(http.Dir(config.Dir))))
	http.HandleFunc("/upload", UploadHandler)
	err = http.ListenAndServe(":80", nil)
	if err != nil {
		log.Println(err.Error())
	}
}

func UploadHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/json; charset=utf-8")
	// 判断是不是POST方法
	if r.Method != "POST" {
		w.WriteHeader(http.StatusBadRequest)
		_, err := w.Write([]byte(utils.JsonRes(3000, "必须使用POST方法上传图片")))
		if err != nil {
			log.Println(err.Error())
		}
		return
	}
	err := r.ParseMultipartForm(config.MaxSize)
	if err != nil {
		log.Println(err.Error())
		w.WriteHeader(http.StatusBadRequest)
		_, err := w.Write([]byte(utils.JsonRes(3001, "上传图片大小不能超过20M")))
		if err != nil {
			log.Println(err.Error())
		}
		return
	}
	// 校验appkey和appsecret
	key := r.FormValue("app_key")
	secret := r.FormValue("app_secret")
	if key == "" || secret == "" {
		w.WriteHeader(http.StatusBadRequest)
		_, err := w.Write([]byte(utils.JsonRes(3002, "缺少app_key和app_secret参数")))
		if err != nil {
			log.Println(err.Error())
		}
		return
	}
	if utils.Md5Encode(key) != config.AppKey || utils.Md5Encode(secret) != config.AppSecret {
		w.WriteHeader(http.StatusBadRequest)
		_, err := w.Write([]byte(utils.JsonRes(3004, "app_key或app_secret无效")))
		if err != nil {
			log.Println(err.Error())
		}
		return
	}
	// 获取image
	file, headers, err := r.FormFile("image")
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		_, err := w.Write([]byte(utils.JsonRes(3005, err.Error())))
		if err != nil {
			log.Println(err.Error())
		}
		return
	}
	fileBytes, err := ioutil.ReadAll(file)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		_, err := w.Write([]byte(utils.JsonRes(3006, err.Error())))
		if err != nil {
			log.Println(err.Error())
		}
		return
	}
	// 判断文件类型
	fileType := http.DetectContentType(fileBytes)
	if fileType != "image/jpeg" && fileType != "image/jpg" &&
		fileType != "image/gif" && fileType != "image/png" {
		w.WriteHeader(http.StatusBadRequest)
		_, err := w.Write([]byte(utils.JsonRes(3007, "文件类型错误")))
		if err != nil {
			log.Println(err.Error())
		}
		return
	}
	// 如果不存在就创建
	os.MkdirAll(config.Dir, 0666)
	split := strings.Split(headers.Filename, ".")
	uid := uuid.New().String()
	uid = strings.ReplaceAll(uid, "-", "")
	fileName := uid + "." + split[len(split)-1]
	err = ioutil.WriteFile(config.Dir+"/"+fileName, fileBytes, 0666)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		_, err := w.Write([]byte(utils.JsonRes(3008, err.Error())))
		if err != nil {
			log.Println(err.Error())
		}
		return
	}
	defer file.Close()
	res := utils.Result{
		Code:      2000,
		Url:       config.BaseUrl + fileName,
		Timestamp: time.Now().Format("2006-01-02 15:04:05"),
	}
	j, err := json.Marshal(res)
	if err != nil {
		log.Println(err.Error())
	}
	log.Println("file upload success : ", res.Url)
	w.Write(j)
}






